const allCity = new City();
const vm = new Vue({
    el: '#main',
    data: {
        allCity: allCity.province.sort((a, b) => {
            return a.text.length - b.text.length;
        }),
        hotCity: [],
        selectProvince: '', // 选中的省份
        subCity: [], // 选中的省份下的市
        proposeCity: [],
    },
    methods: {
        setSelectProvince,
        inputCity,
        clearIpt,
        selectCity,
    },
});

if (fxj.deBug) {
    main();
}

function apiready() {
    main().catch(
        e => {
            console.error(e);
        },
    );
}

async function main() {
    fxj.fixLayout();
    mui.init();
    getHotCity();
}

function setSelectProvince(evt, p) {
    if (vm.selectProvince) {
        vm.selectProvince.active = false;
    }
    p.active = true;
    vm.selectProvince = p;
    vm.subCity = allCity.getCityByProvince({id: p.value}).sort((a, b) => {
        return a.text.length - b.text.length;
    });
    setTimeout(() => {
        window.scrollTo(0, document.body.offsetHeight);
    }, 50);
}

function inputCity(e) {
    let value = e.target.value;
    vm.proposeCity = [];
    if (!value) return;
    if (e.keyCode === 13 || e.code === 'Enter') {
        searchIptCity(value);
    }
    else {
        showSuggest(value);
    }
}

function showSuggest(value) {
    for (let [k, id] of Object.entries(SEARCH_CITY)) {
        if (k.includes(value)) {
            vm.proposeCity.push({
                name: k,
                id,
            });
        }
    }
}

function searchIptCity(value) {
    for (let [k, id] of Object.entries(SEARCH_CITY)) {
        if (k === value) {
            selectCity(id, k);
            return;
        }
    }
    toast(`没有找到城市: ${value}`);
}

function clearIpt() {
    const ipt = document.getElementById('iptSearch');
    ipt.value = '';
    clearIpt = () => {
        ipt.value = '';
    };
}

async function getHotCity() {
    const result = await ajax({
        url: 'home/index/getHotCity',
    });
    vm.hotCity = result.data;
}

function selectCity(id, cityName) {
    goPage('search_housing.html', {
            data: {
                id,
                cityName,
            },
        },
    );
}